package com.chookss.video;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.aliyun.apsara.alivclittlevideo.net.NetWatchdog;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.chookss.R;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.WatermarkEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.Utils;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.model.VideoModel;
import com.chookss.video.model.VideoSourceModel;
import com.chookss.video.util.VideoUtils;
import com.chookss.view.WaterMarkBg;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;

import static android.content.Context.POWER_SERVICE;

/**
 * 视频列表
 */
public class VideoFragment extends ImmersionFragment {

    private static final String TAG = "VideoFragment";

    private AlivcVideoPlayView videoPlayView;
    private ImageView ivWatermark;
    protected VideoModel videoModel;
    protected boolean isStoped = false;

    private NetWatchdog netWatchdog;
    private int num = 0;
    private String lpFlag = "";//0禁止1正常
    public VideoFragment() {

    }

    @Override
    public void initImmersionBar() {

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_video, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        videoModel = ViewModelProviders.of(this).get(VideoModel.class);
        // 网络监听
        initNetWatchDog();
        //注册接受
        EventBus.getDefault().register(this);
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        //初始化页面
        initView();
        // 注册编辑完成之后跳转的页面
        loadPlayList(false);
    }

    /**
     * 网络监听
     */
    public void initNetWatchDog() {
        netWatchdog = new NetWatchdog(getContext());
        netWatchdog.setNetConnectedListener(new MyNetConnectedListener(getActivity()));
    }


    private void showSetsDialog(VideoEntity model) {
        Intent intent = new Intent(getContext(), VideoSetsPlayActivity.class);
        intent.putExtra("video", model);
        intent.putExtra("watermark", "4");
        intent.putExtra("type", "1");
        startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("refreshAccount".equals(msg)) {
                //更新账户了
                loadPlayList(false);
                WatermarkEntity watermarkEntity = NavigationTools.getWaterMark(this.getContext(), "2");
                if (watermarkEntity != null) {
                    if ("1".equals(watermarkEntity.getStatusCd())) {
                        WaterMarkBg.setWaterBg(this.getContext(), ivWatermark, new ShareUtils().getString(this.getContext(), StaticClass.USER_NICKNAME, "") + new ShareUtils().getString(this.getContext(), StaticClass.APPACCOUNT, ""), watermarkEntity.getCompanyWatermarkName(), false);

                    }
                }
            }
        }
    }

    /**
     * 初始化View
     */
    protected void initView() {
        lpFlag = new ShareUtils().getString(getActivity(), StaticClass.LP_FLAG, "1");
        //禁止截屏
        if ("0".equals(lpFlag)) {
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
        videoPlayView = findViewById(R.id.video_play);
        ivWatermark = findViewById(R.id.ivWatermark);

        WatermarkEntity watermarkEntity = NavigationTools.getWaterMark(this.getContext(), "2");
        if (watermarkEntity != null) {
            if ("1".equals(watermarkEntity.getStatusCd())) {
                WaterMarkBg.setWaterBg(this.getContext(), ivWatermark, new ShareUtils().getString(this.getContext(), StaticClass.USER_NICKNAME, "") + new ShareUtils().getString(this.getContext(), StaticClass.APPACCOUNT, ""), watermarkEntity.getCompanyWatermarkName(), false);

            }
        }

        videoPlayView.setOnRefreshDataListener(new AlivcVideoListView.OnRefreshDataListener() {
            @Override
            public void onRefresh() {

                loadPlayList(false);
            }

            @Override
            public void onLoadMore() {
                num++;
                loadPlayList(true);
            }
        });
        videoPlayView.setOnItemBtnClick(new OnVideoButtonClickListener(videoModel, this) {
            @Override
            public void onVideoClick(@NotNull View v, View tvComment, int position, @NotNull VideoEntity entity) {
                if (v.getId() == R.id.tvSetsInfo) {
                    showSetsDialog(entity);
                    return;
                }
                super.onVideoClick(v, tvComment, position, entity);
            }
        });
        videoPlayView.setOnItemBtnClick(new OnVideoButtonClickListener(videoModel, this));
    }

    private <T> T findViewById(int id) {
        return (T) getView().findViewById(id);
    }

    public void loadPlayList(boolean isLoadMoreData) {
        int pageSize = 10;
        if (!isLoadMoreData) {
            num = 0;
        }
        if (videoModel == null) {
            return;
        }

        if (videoPlayView == null) {
            return;
        }
        videoModel.getVideoRandByFans(num, pageSize).observe(getViewLifecycleOwner(), result -> {
            if (result.data != null && videoPlayView != null) {
                List<VideoSourceModel> models = VideoUtils.videoEntityToModel(result.data);
                if (!isLoadMoreData) {
                    videoPlayView.refreshVideoList(models, result.data.size() < pageSize);
                } else {
                    videoPlayView.addMoreData(models, result.data.size() < pageSize);
                }
            } else {
                if (videoPlayView != null) {
                    videoPlayView.loadFailure();
                }
                try {
                    if (result.error != null) {
                        ToastUtils.show(getActivity(), result.error.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setStoped(boolean stoped) {
        isStoped = stoped;
        resumeOrPauseVideo();
    }

    private void resumeOrPauseVideo() {


        if (videoPlayView == null) {
            return;
        }
        if (isResumed() && getUserVisibleHint() && !isHidden() && !isStoped) {
            videoPlayView.onResume();
        } else {
            videoPlayView.onPause();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        resumeOrPauseVideo();
    }

    @Override
    public void onPause() {
        super.onPause();
        resumeOrPauseVideo();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        resumeOrPauseVideo();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        resumeOrPauseVideo();
    }

    @Override
    public void onStart() {
        super.onStart();
        netWatchdog.startWatch();
    }

    @Override
    public void onStop() {
        super.onStop();
        netWatchdog.stopWatch();
    }

    @Override
    public void onDestroy() {
        if (videoPlayView != null) {
            videoPlayView.setOnRefreshDataListener(null);
            videoPlayView.onDestroy();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
